using System;
using System.Collections;
using Iivil.Infrastructure.Logging;

namespace Iivil.Infrastructure.Logging.Providers
{
	/// <summary>
	/// Summary description for UserLogProvider.
	/// </summary>
	public class UserLogProvider : ILogWriter {
        private Queue _cache;
        private struct LogMessage {
            public DateTime t;
            public Severity s;
            public string c;
            public string m;
            public LogMessage(DateTime time, Severity severity, string category, string message) {
                t = time;
                s = severity;
                c = category;
                m = message;
            }
        }
		public UserLogProvider() {
		}

	    public void WriteLogEntry(Severity severity, string category, string formatMessage, params object[] arg) {
	        WriteLogEntry(severity, category, string.Format(formatMessage, arg));
	    }

	    public void WriteLogEntry(Severity severity, string category, string message) {
//            StackTrace st = new StackTrace();
//            StackFrame sf = st.GetFrame(2);
//            Debug.WriteLine(sf.GetMethod());

	        if (LogWriteEvent != null)
                LogWriteEvent(DateTime.Now, severity,  category, message);
            else {
	            if (_cache == null)
                    _cache = new Queue();
                _cache.Enqueue(new LogMessage(DateTime.Now, severity,  category, message));
	        }
	    }

	    public void Dispose() {
	        return;
	    }

        public delegate void LogWriteEventHandler(DateTime time, Severity severity, string category, string message);

	    private LogWriteEventHandler _logWriteEvent;

	    public LogWriteEventHandler LogWriteEvent {
	        get {
	            return _logWriteEvent;
	        }
	        set {
                if (_logWriteEvent == null && _cache != null && value != null)
                    while (_cache.Count > 0) {
                        LogMessage lm = (LogMessage) _cache.Dequeue();
                        value(lm.t, lm.s, lm.c, lm.m);
                    }
                //else if (value == null)
                //    _cache = null;
	            _logWriteEvent = value;
	        }
	    }


	}
}
